package org.example.ch04;

import org.example.ch04.tree.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的中序遍历
 */
public class inorderTraversal {
    public static void main(String[] args) {



       TreeNode leftNode = new TreeNode(3,null,null);

       TreeNode rightNode = new TreeNode(2, leftNode,null);

        TreeNode root = new TreeNode(1,null,rightNode);

//        List<Integer> list = inorderTraversal(root);
        List<Integer> list = solution1(root);
        for (Integer i:list){
            System.out.println(i);
        }


    }


    public static List<Integer> inorderTraversal(TreeNode root){
        List<Integer> res = new ArrayList<Integer>();
        inorder(root,res);
        return res;
    }

    public static void inorder(TreeNode root,List<Integer> res){
        //把递归的终止条件写出来
        if(root == null){
            return;
        }
        inorder(root.left,res);
        res.add(root.getVal());
        inorder(root.right,res);
    }

    public static List<Integer> solution1(TreeNode root){
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        while (root!=null || !stack.isEmpty()){
            while (root!=null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.getVal());
            root = root.right;
        }
        return res;
    }
}
